<template>
    <div class="wrapper">
        <div class="header">
            <el-row style="margin-bottom:20px">
                <el-button type="danger" style="width:120px" @click="centerDialogVisible=true;title='新增'">新建</el-button>
            </el-row>
             <el-row>
                <el-col :span="4" style="margin-right:30px">
                    <el-input placeholder="脚本名称" v-model="searchBo.taskName"></el-input>
                </el-col> <el-button type="danger" style="width:120px" @click="getList">查询</el-button>
            </el-row>
        </div>
        <div class="body">
            <Table :list="list" :state="false" v-loading="loading" :total="total" @sizeChange="handSize" @currentChange="currentChange">
                <slot>
                     <el-table-column label="操作" align="center">
                        <template slot-scope="scope">
                            <el-button
                                size="mini"
                                type="primary"
                                @click="handleEdit(scope.row)">修改
                            </el-button>
                            <el-button
                                size="mini"
                                type="danger"
                                @click="handleDel(scope.row)">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </slot>
            </Table>
        </div>
        <el-dialog
            :title="title"
            :visible.sync="centerDialogVisible"
             :before-close="onCancel"
            width="30%"
            >
            <div>
                <el-form ref="addForm" :model="addForm" :rules="rule" label-position="right" label-width="140px">
                    <el-form-item label="指令名称" prop='name'>
                        <el-input v-model="addForm.name" placeholder="请输入指令簇名称"></el-input>
                    </el-form-item>
                    <el-form-item label="指令编码" v-for="(item,index) in addForm.list" :key="index" :prop='"list."+index+".value"'
                        :rules="{required:true,message:'该项不能为空'}"
                    >
                         <el-select clearable v-model="item.value" placeholder="请选择执行脚本">
                            <el-option
                            v-for="item in contentList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                            </el-option>
                        </el-select>
                        <el-button  icon="el-icon-plus" type="success" @click="addItem"></el-button>
                        <el-button  icon="el-icon-minus" type="danger" @click="minusItem(index)"></el-button>
                        <!-- <el-input v-model="addForm.value" placeholder="请输入指令簇编码"></el-input> -->
                    </el-form-item>
                    <el-form-item label="备注" prop='remark'>
                        <el-input v-model="addForm.remark" placeholder="请输入备注"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="onCancel">取 消</el-button>
                <el-button type="primary" @click="onOk">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {scriptList,scriptAdd,
scriptEdit,scriptDel,directiveList

} from '../../../api/facility'
import Socket from '../../../utils/socket'
import Table from '@/components/Table'
import {getToken} from  '../../../utils/auth'
export default {
    components:{
        Table
    },
    data () {
        let validPassword=(rule,value,callback)=>{
            // let reg= /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{1,99}$/
            // if(!reg.test(value)){callback(new Error('只允许字母和数字'))
            // }else{
            //     callback()
            // }
            try{
                var obj = JSON.parse(value);
                    if(typeof(obj) ==='object'){
                        callback()
                    }else{
                        callback(new Error('请输入正确的JSON字符串！'))
                    }
            }catch(err) {
                callback(new Error('请输入正确的JSON字符串'))
            }
             
        };
        return {

            list:{
                thead:[
                    // {label:'编号',prop:"index",rowspan:1},
                    {label:'指令簇名称',prop:"name",rowspan:1},
                    {label:'指令簇编码',prop:"value",rowspan:1},
                    {label:'备注',prop:"remark",rowspan:1},
                ],
                tbody:[]
            },
            loading:false,
            total:0,
            title:'新增',
            centerDialogVisible:false,
            addForm:{
                name:'',
                list:[{
                    value:''
                }],
                remark:''
            },
            rule:{
                name:[  { required: true, message: '请输入指令簇名称', trigger: 'blur' },],
                // value:[  { required: true, message: '请输入指令簇编码', trigger: 'blur' },
                // // {
                // //    validator :validPassword, trigger: 'blur'
                // // }
                // ],
                remark:[  { required: true, message: '请输入备注', trigger: 'blur' },]
            },
            pageSize:20,
            pageNum:1,
            total:0,
            searchBo:{},
            socket:null,
            contentList:[]

        }
        
    },
    mounted () {
        this.getList();
        directiveList({
            pageNum:1,
            pageSize:0
        }).then(res=>{
            if(res.status =='200'){
                this.contentList = [...res.data.list]
            }
        });
        this.socket = new Socket({
            url:'ws://dev-ws.sqcat.cn/device-client/'+getToken(),
            callback:this.onMessage
        })
    },
    methods:{
        onOk () {
            this.$refs['addForm'].validate((vaild)=>{
                if(vaild) {
                    let list = this.addForm.list.map(item=>{
                            return item.value*1
                        });
                    let obj = {
                        name:this.addForm.name,
                        remark:this.addForm.remark,
                        instructionIds:list.join(','),
                        
                    }
                    if(this.title == '新增'){
                        scriptAdd(obj).then(res=>{
                            if(res.status == 200) {
                                this.$message({
                                    type:'success',
                                    message:"新增成功！"
                                })
                                this.getList()
                                this.onCancel()
                            }else{
                                this.$message.error(res.msg)
                            }
                        })
                    }else{
                        obj.id = this.addForm.id;
                         scriptEdit(obj).then(res=>{
                            if(res.status == 200) {
                                this.$message({
                                    type:'success',
                                    message:"修改成功！"
                                })
                                this.getList()
                                this.onCancel()
                            }else{
                                this.$message.error(res.msg)
                            }
                        })
                    }
                }
            })
           
        },
        onCancel () {
            this.centerDialogVisible = false;
            this.addForm=this.$options.data().addForm;
            this.$refs['addForm'].clearValidate();
            this.$refs['addForm'].resetFields();
        },
        addItem () {
            
            this.addForm.list.push({value:''})
            this.addForm = {...this.addForm}
            // this.$forceUpdate()
        },
        minusItem (idx) {
            
            // this.addForm.list.pop()
            //  var index = this.addForm.list.indexOf(idx)
            // if (index !== -1) {
                if(this.addForm.list.length ==1){
                    return 
                }
            this.addForm.list.splice(idx, 1)
            // }
        },
        onMessage (data) {
            this.socket.heartCheck()
        },
        getList () {
            this.loading = true;
            let obj = {
                pageNum:this.pageNum,
                pageSize:this.pageSize,
                ...this.searchBo
            }
            scriptList(obj).then(res=>{
                if(res.status == 200) {
                    this.total = res.data.total;
                    this.list.tbody = res.data.list;
                    
                }
            }).finally(res=>{
                this.loading =false;
            })
        },
        handSize (val) {
            this.pageNum = val;
            this.getList()
        },
        currentChange (val) {
            this.pageSize = val;
            this.getList()
            console.log('currentChange',val)
        },
        handleEdit (row) {
            this.title = '修改'
            this.addForm = {...row};
            let list = row.instructionIds.split(',').map(item=>{
                return {
                    value:item*1
                }
            })
            this.addForm.list = list;
            this.addForm = {...this.addForm}

            this.centerDialogVisible = true;
        },
        handleDel (row) {
             this.$confirm('此操作将永久删除该项, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then(() => {
                    scriptDel(row).then(res=>{
                        if(res.data) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.getList()
                        }else{
                            this.$message({
                                type:'error',
                                message:res.msg
                            })
                        }
                    })
                    
                }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        }
    }
}
</script>

<style lang="less" scoped>
    .wrapper{
        width: 100%;
         overflow: auto;
        .header{
            height: 190px;
            margin-bottom: 25px;
            background-color: #fff;
            padding:38px 20px;
            box-sizing: border-box;;
        }
        .body{
            width: 100%;
            height:500px ;
            box-sizing: border-box;
            padding:10px 20px;
            overflow: auto;
            background-color: #fff;
        }
        

    }
</style>